package servlet.admin;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import dao.ItemDao;

import pojo.ItemAttr;
import servlet.ServletTemplate;
import util.Helper;

public class AddItem extends ServletTemplate{
    /**
     * 执行POST操作 
     */
    public void doPost(HttpServletRequest request,
                         HttpServletResponse response) throws IOException, ServletException{
        super.doPost(request, response);
        
        if(false == this.isLogin() || false == this.isAdmin()) {
            this.setRequestAttr("errorInfo", "非法访问！");
            this.forward("hint.jsp");
            return ;
        }
        
        ItemAttr itemAttr       = this.genItemAttr();
        String validateResult   = itemAttr.validate();
        if(validateResult != null) {
            this.setRequestAttr("errorInfo", validateResult);
            this.forward("../hint.jsp");
        }
        ItemDao itemDao         = new ItemDao();
        if(true == itemDao.insert(itemAttr)) {
            this.setRequestAttr("hintInfo", "添加投票项目成功！");
        } else { 
            this.setRequestAttr("errorInfo", "添加失败！");
        } 
        //清除用户的登陆有效时间
        this.forward("hint.jsp");
    }
    
    /**
     * 得到项目属性对象 
     */
    public ItemAttr genItemAttr() {
        ItemAttr itemAttr   = new ItemAttr();
        itemAttr.setItemPoll(0);
        itemAttr.setCreateTime(Helper.getNowTime());
        itemAttr.setItemName((String)this.getRequestParam("item_name"));
        return itemAttr;
    }
}
